<template>
  <div v-show="isShow">
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>信息流管理</el-breadcrumb-item>
      <el-breadcrumb-item>
        <span
          class="u-cursor"
          @click="$router.back()"
        >开票信息管理</span>
      </el-breadcrumb-item>
      <el-breadcrumb-item>{{pageTitle}}开票</el-breadcrumb-item>
    </el-breadcrumb>
    <Container class="u-pb60">
      <el-form
        class="m-form--detail"
        label-width="160px"
        :model="pageData"
        :rules="pageRules"
        ref="pageForm"
      >
      <ContainerTitle>发票信息</ContainerTitle>
        <el-form-item
          required
          prop="invoiceStatus"
          size="small"
          label="发票状态："
        >
          <el-select
            class="u-w350"
            placeholder="请选择发票状态"
            filterable
            :disabled="['detail'].includes(pageAction)"
            v-model="pageData.invoiceStatus"
          >
            <el-option
              v-for="item in INVOICESTATEDATA"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          required
          prop="invoiceNumber"
          size="small"
          label="发票号码："
        >
          <el-input
            class="u-w350"
            placeholder="请输入发票号码"
            :disabled="pageAction === 'detail'"
            v-model="pageData.invoiceNumber"
          ></el-input>
        </el-form-item>
        <el-form-item
          size="small"
          label="申请发票日期："
        >
         <el-date-picker
            class="u-w350"
            type="date"
            placeholder="请选择申请发票日期"
            value-format="yyyy-MM-dd"
            :disabled="pageAction === 'detail'"
            v-model="pageData.applyInvoiceDate"
          >
         </el-date-picker>
        </el-form-item>
         <el-form-item
          size="small"
          label="开票日期："
        >
         <el-date-picker
            class="u-w350"
            type="date"
            placeholder="请选择开票日期"
            value-format="yyyy-MM-dd"
            :disabled="pageAction === 'detail'"
            v-model="pageData.invoiceDate"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item
          size="small"
          label="开票金额（元）："
        >
          <el-input
            class="u-w350"
            placeholder="请输入开票金额（元）"
            :disabled="pageAction === 'detail'"
            type="Number"
            v-model="pageData.invoiceAmount"
          ></el-input>
        </el-form-item>
        

        <ContainerTitle>结算单信息</ContainerTitle>
         <el-form-item label-width="88px">
          <el-alert
            class="u-w500"
            type="warning"
            :closable="false"
            v-if="['create', 'edit'].includes(pageAction)"
          >
            1、注意！点击选择结算单，已选的结算单数据将被清空！必须从新选择结算单!
          </el-alert>
        </el-form-item>
        <el-form-item
          size="small"
          label="结算单："
        >
          <el-button 
          size="mini" 
          type="primary"
          :disabled="['detail'].includes(pageAction)"
          @click="handleChooseStatements"
          >选择</el-button>
          
        </el-form-item>
        <el-form-item
          size="small"
          label=""
          label-width="70px"
        >
          <Container>
            <!-- 表格 -->
            <el-table
              border
              stripe
              :data="tableData"
            >
              <el-table-column
                align="center"
                v-for="(item, index) in filterTableColumn"
                :label="item.label"
                :key="index"
              >
                <template slot-scope="scope">
                  
                  <!-- 结算周期 -->
                  <template v-if="item.rederStatus">{{ scope.row[item.reder[0]] +'-'+ scope.row[item.reder[1]] }}</template>
                  <!-- 结算方式 -->
                  <template v-else-if="item.prop === 'settleWay'">{{ mapOptionLabel(SETTLEWAY,scope.row.settleWay) }}</template>
                  <!-- 发票状态 -->
                  <template v-else-if="item.prop === 'invoiceStatus'">{{ mapOptionLabel(INVOICESTATEDATA,scope.row.invoiceStatus) }}</template>

                  <!-- <template v-else-if="item.prop === 'settlementAmount'">{{scope.row.settlementAmount == null ? 0 : scope.row.settlementAmount}}</template> -->
                  <!-- 其他 -->
                  <template v-else>{{scope.row[item.prop]}}</template>
                </template>
              </el-table-column>
            </el-table>
          </Container>
          <!-- 表格 -->
        </el-form-item>
        <!-- 判断如果没有客户全称值；隐藏 -->
        <div v-if=" InvoiceCustomer.taxpayerRegistr ">
          <ContainerTitle>开票客户信息</ContainerTitle>
          
          <el-form-item label="纳税人登记号：">{{InvoiceCustomer.taxpayerRegistr}}</el-form-item>
          <el-form-item label="开户行：">{{InvoiceCustomer.depositBank}}</el-form-item>
          <el-form-item label="银行账号：">{{InvoiceCustomer.bankAccount}}</el-form-item>
          <el-form-item label="开户地址：">{{InvoiceCustomer.depositAddress}}</el-form-item>
          <el-form-item label="开票电话：">{{InvoiceCustomer.invoicePhone}}</el-form-item>
        </div>
        <div>
          <ContainerTitle>发票邮寄信息</ContainerTitle>
          <el-form-item
            size="small"
            label="发票运单号："
          >
            <el-input
              class="u-w350"
              placeholder="请输入发票运单号"
              :disabled="pageAction === 'detail'"
              v-model="pageData.courierNumber"
            ></el-input>
          </el-form-item>
          <el-form-item
            size="small"
            label="快递公司："
          >
            <el-select
              class="u-w350"
              placeholder="请选择快递公司"
              filterable
              :disabled="['detail'].includes(pageAction)"
              v-model="pageData.courier"
            >
              <el-option
                v-for="item in COURLERDATA"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item
            size="small"
            label="寄出日期："
          >
          <el-date-picker
              class="u-w350"
              type="date"
              placeholder="请选择寄出日期"
              value-format="yyyy-MM-dd"
              :disabled="pageAction === 'detail'"
              v-model="pageData.sendingDate"
            >
          </el-date-picker>
          </el-form-item>
          <el-form-item
            size="small"
            label="送达地址："
          >
            <el-input  
            class="u-w350"
            type="textarea" 
            v-model="pageData.mailAddress"
            :disabled="['detail'].includes(pageAction)"
            maxlength="200"
            rows="5"
            ></el-input>
          </el-form-item>
        </div>
        <div>
          <ContainerTitle class="fl">回款信息</ContainerTitle> 
          <!-- <el-button class="fl" size="small" type="primary" :disabled="['detail'].includes(pageAction)"  style="margin-left:100px" @click="addReturnMoney()">添加</el-button> -->
        </div>
        <div v-for="(item,index) in pageData.invoiceReturnedMoney" :key="index" class="addModule">
          <el-form-item
            size="small"
            label="已回款金额（元）"
          >
            <el-input
              class="u-w350"
              placeholder="请输入已回款金额（元）"
              :disabled="pageAction === 'detail'"
              type="Number"
              v-model.trim="item.returnedMoney"
            ></el-input>
            <el-button size="small" @click="delReturnMoney(index)" class="del" v-if="index !== 0" :disabled="['detail'].includes(pageAction)">删除</el-button>
          </el-form-item>
           <el-form-item
            size="small"
            label="回款日期："
          >
            <el-date-picker
              class="u-w350"
              type="date"
              placeholder="请选择回款日期"
              value-format="yyyy-MM-dd"
              :disabled="pageAction === 'detail'"
              v-model.trim="item.returnedMoneyDate"
            >
            </el-date-picker>
        </el-form-item>
        </div>
        <!-- <el-form-item
            size="small"
            label="已回款总金额（元）"
          >
            {{AllMoney}}
          </el-form-item> -->
        <el-form-item
            size="small"
            label="备注"
          >
            <el-input  
            class="u-w350"
            type="textarea" 
            v-model="pageData.remarks"
            :disabled="['detail'].includes(pageAction)"
            maxlength="1000"
            rows="5"
            ></el-input>
          </el-form-item>
      </el-form>

    </Container>
    <Affix :offset-bottom="0">
      <ButtonGroup
        isFixed
        align="right"
      >
        <el-button
          size="small"
          @click="$router.back()"
        >返回</el-button>
        <el-button
          size="small"
          type="primary"
          v-if="['create', 'edit'].includes(pageAction)"
          @click="handleEnsure"
        >确定</el-button>
      </ButtonGroup>
    </Affix>
  </div>
  <!-- <InvoiveDatements v-show="!isShow"></InvoiveDatements> -->
</template>
<style>
  .fl{display: inline-block;}
  .addModule{
    margin-top:40px;
  }
  .del{
    margin-left:20px;
  }
</style>


<script>
import ContainerTitle from "@/components/container-title";
import Container from "@/components/container";
import Affix from "@/components/affix";
import ButtonGroup from "@/components/button-group";
// import InvoiveDatements from '@/pages/flow/invoive-statements';

import { mapOptionLabel } from "@/util";
import { OPERATOR_OPTION,INVOICESTATEDATA,SETTLEWAY,COURLERDATA} from "@/assets/js/flow-option";

export default {
  components: {
    ContainerTitle,
    Container,
    Affix,
    ButtonGroup,
    // InvoiveDatements
  },
  data() {
    return {
      OPERATOR_OPTION,
      INVOICESTATEDATA,
      SETTLEWAY,
      COURLERDATA,
      pageAction: this.$route.query.action,
      
     isShow:true,
      // 下拉
      platformOptions: [],
      customerOptions: [],
      productOptions: [],
      pageData:{
        invoiceStatus:null,
        invoiceNumber:null,
        applyInvoiceDate:null,
        invoiceDate:null,
        invoiceAmount:null,
        statementIds:this.$route.query.statementIds||null,
        customerFullNameId:this.$route.query.customerFullNameId||null,
        id:this.$route.query.id || null,
        courier:null,
        courierNumber:null,
        sendingDate:null,
        mailAddress:null,
        remarks:null,
        invoiceReturnedMoney:[{
          returnedMoney:0,
          returnedMoneyDate:''
        }],
      },
      statementsList:{},
      tableData:[],
      tableSelectionData: [],
      tableColumn: [
        {
          label: "结算单号",
          prop: "billId",
          visible: true
        },
        {
          label: "结算周期",
          prop: "startDate",
          rederStatus:true,
          reder:['startDate','endDate'],
          visible: true
        },
        {
          label: "客户全称",
          prop: "customerFullName",
          visible: true
        },
        {
          label: "结算方式",
          prop: "settleWay",
          visible: true
        },
        {
          label: "实际结算金额（元）",
          prop: "settlementAmount",
          visible: true
        },
        {
          label: "发票状态",
          prop: "invoiceStatus",
          visible: true
        }
      ],
      page: {
        pageNo: 1,
        pageSize: 50
      },
      pageTotal: 0,
      InvoiceCustomer:{
        taxpayerRegistr:''
      },
      pageRules: {
        invoiceStatus: {
          required: true,
          message: "请选择发票状态",
          trigger: ["change", "blur"]
        },
        invoiceNumber: {
          required: true,
          message: "请输入发票号码",
          trigger: ["change", "blur"]
        }
      }
    };
  },
  computed: {
    AllMoney(){
      // 计算已回款总金额
      let arr = this.pageData.invoiceReturnedMoney,
          sum
      sum = arr.reduce(function(total,curr) {
          return total + curr.returnedMoney*1;
      },0)
      return sum
    },
    filterTableColumn() {
      return this.tableColumn.filter(item => item.visible);
    },
    pageTitle() {
      return {
        create: "新增",
        edit: "编辑",
        detail: "查看"
      }[this.pageAction];
    }
  },
  methods: {
    mapOptionLabel,
    delReturnMoney(index){
      this.pageData.invoiceReturnedMoney.splice(index, 1);
    },
    addReturnMoney() {
      this.pageData.invoiceReturnedMoney.push({
        returnedMoney:0,
        returnedMoneyDate:''
      });
    },
    //获取列表
    getTable() {
      this.$http({
        method: "get",
        url: "/manage/api/bus/statements/get_list_by_ids",
        params: {
          billIds: this.pageData.statementIds
        }
      }).then(res => {
        if (res.data.code === 0) {
          this.pageData.statementIds = this.$route.query.statementIds
          this.tableData = res.data.data.list;
          this.pageData.customerFullNameId = res.data.data.list[0].customerFullNameId
          this.getInvoiceCustomerInfo(this.pageData.customerFullNameId)
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    mapOptionValue(data, name) {
      let item = data.find(item => item.name === name);
      if (item) {
        return item.id;
      }
      return "-";
    },
    handleChooseStatements(){
      //清除接口
      sessionStorage.setItem('pageData',JSON.stringify(this.pageData))
      if(!this.tableData.length>0){
        this.$router.push({
          name: 'flow-invoice-statements',
          query: {
            action: this.pageAction,
            statementIds: this.pageData.statementIds,
            customerFullNameId:this.pageData.customerFullNameId
          }
        })
      }else{
        this.$confirm('点击 确定选择后，已选择的结算单数据将被清空！必须重新选择结算单，否则无结算单数据！', '选择结算单', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$router.push({
            name: 'flow-invoice-statements',
            query: {
              action: this.pageAction,
              statementIds: this.pageData.statementIds
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消选择'
          });          
        });
      }
      if(this.pageAction == 'detail'){
        this.removeStatements()
      }
    },
    removeStatements(){
      this.$http({
        method: "get",
        url: "/manage/api/bus/statements/get_list_by_ids",
        params: {
          id:this.pageData.id,
          billIds: this.pageData.statementIds
        }
      }).then(res => {
        if (res.data.code === 0) {
          // this.tableData = res.data.data.list;
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    // 下拉
    fetchPlatformOptions() {
      this.$http({
        method: "get",
        url: "/manage/api/bus/platform/get_platform",
        params: {
          status: 2,
          customerId: 0,
          productId: 0
        }
      }).then(res => {
        if (res.data.code === 0) {
          this.platformOptions = res.data.data;
        }
      });
    },
    fetchCustomerOptions() {
      this.$http({
        method: "get",
        url: "/manage/api/bus/customer/get_customer_full_name",
        params: {
          status: 2,
          platformId: 0
        }
      }).then(res => {
        if (res.data.code === 0) {
          this.customerOptions = res.data.data;
         
        }
      });
    },
    fetchProductOptions(platformId = 0, customerId = 0) {
      this.$http({
        method: "get",
        url: "/manage/api/bus/product/get_no_stop_product",
        params: {
          platformId: Number(platformId),
          customerId: Number(customerId)
        }
      }).then(res => {
        if (res.data.code === 0) {
          this.productOptions = res.data.data;
        }
      });
    },
    handleChangePlatformOptions() {
      this.pageData.customerId = null;
      this.pageData.productId = null;
      this.fetchCustomerOptions();
    },
    handleChangeCustomerOptions() {
      this.pageData.productId = null;
      this.fetchProductOptions(this.pageData.platformId, this.pageData.customerId);
    },
    // 根绝客户全称获取发票客户信息
    getInvoiceCustomerInfo(){
      this.$http({
        method: "get",
        url: "/manage/api/bus/customer_aptitude/get_by_id",
        params: {
         customerAptitudeId:this.pageData.customerFullNameId
        }
      }).then(res => {
        if (res.data.code === 0) {
          let data = res.data.data;
          this.InvoiceCustomer = data;
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    // 确定
    handleEnsure() {
      if (this.pageAction === "edit") {
        this.updateDetail();
      } else {
        this.createDetail();
      }
    },
    // 新建
    createDetail() {
      this.$refs.pageForm.validate(valid => {
        if (valid) {
          this.$http({
            method: "post",
            url: "/manage/api/bus/invoice/add",
            data: this.pageData
          }).then(res => {
            if (res.data.code === 0) {
              this.$message.success("新建成功！");
              this.$router.push({
                name: 'flow-invoice',
              });
            } else {
              this.$message.error(res.data.msg);
            }
          });
        }
      });
    },
    // 编辑
    updateDetail() {
      this.$refs.pageForm.validate(valid => {
        if (valid) {
          this.$http({
            method: "post",
            url: "/manage/api/bus/invoice/update",
            data:{
              ...this.pageData,
            } 
          }).then(res => {
            if (res.data.code === 0) {
              this.$message.success("修改成功！");
              this.$router.push({
                name: 'flow-invoice',
              });
            } else {
              this.$message.error(res.data.msg);
            }
          });
        }
      });
    },
    // 详情
    getDetail() {
      this.$http({
        method: "post",
        url: "/manage/api/bus/invoice/get_by_id",
        params: {
          id: this.$route.query.id
        }
      }).then(res => {
        if (res.data.code === 0) {
          let {
              invoiceStatus,
              invoiceNumber,
              applyInvoiceDate,
              invoiceDate,
              invoiceAmount,
              statementIds,
              customerFullNameId,
              id,
              courier,
              courierNumber,
              sendingDate,
              mailAddress,
              remarks,
              returnedMoney
            } = res.data.data;
            // let invoiceReturnedMoney = 
            this.pageData = {
              invoiceStatus:invoiceStatus*1,
              invoiceNumber,
              applyInvoiceDate,
              invoiceDate,
              invoiceAmount,
              statementIds,
              customerFullNameId,
              id,
              courier,
              courierNumber,
              sendingDate,
              mailAddress,
              remarks,
              invoiceReturnedMoney:returnedMoney
            };
            if(this.pageData.statementIds == '' || this.pageData.statementIds == null){
              return false
            }
            this.getTable()
        }
      });
    },
    // 账号ID
    addAccount() {
      this.pageData.usernameIdList.push({ usernameId: "" });
    },
    removeAccount(index) {
      this.pageData.usernameIdList.splice(index, 1);
    }
  },
  beforeRouteEnter(to, from, next) {
    next(vm=>{          //  这里的vm指的就是vue实例，可以用来当做this使用
      if(from.name == 'flow-invoice-statements'){
        vm.pageData = JSON.parse(sessionStorage.getItem('pageData'))
      }
    })
  },
  created() {
    // this.fetchPlatformOptions();
    this.fetchCustomerOptions();
    if(["create"].includes(this.pageAction)){
      this.pageData.statementIds != null ? this.getTable() :''
    }
   
    if (this.pageAction !== "create") {
      this.fetchProductOptions();
    }
    if (["edit", "detail"].includes(this.pageAction)) {
      //如果是编辑进来的
      // 需要调删除接口
      this.getDetail();
    }
  }
};
</script>